<?php
namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Component\User\Models\User;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Shop;
use iBrand\Shop\Core\Repositories\UserShopRepository;
use iBrand\Component\Card\Repository\CardRepository;

use iBrand\Shop\Core\Repositories\CouponRepository;

use iBrand\Component\Point\Repository\PointRepository;


use iBrand\Component\Point\Model\Point;
use iBrand\Component\User\Models\UserBind;
use iBrand\Server\Exception\UserExistsException;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\OAuthServerException;
use RuntimeException;
use Validator;
use Hash;
use DB;
use iBrand\Shop\Server\Transformers\UserShopTransformer;
use iBrand\Shop\Server\Transformers\CouponsTransformer;
use iBrand\Shop\Server\Transformers\PointTransformer;

class UserController extends Controller
{
    private $userShopRepository;
    private $cardRepository;
    private $couponRepository;
    private $pointRepository;

    public function __construct(
        UserShopRepository $userShopRepository,
        CardRepository $cardRepository,
        CouponRepository $couponRepository,
        PointRepository $pointRepository

    )
    {
        $this->userShopRepository = $userShopRepository;
        $this->cardRepository = $cardRepository;
        $this->couponRepository = $couponRepository;
        $this->pointRepository = $pointRepository;
    }

    public function index()
    {
        $clerk = auth('clerk')->user();
        if ($res = $this->userShopRepository->getUserListPaginateByShopID($clerk->shop_id)) {
            return $this->response()->paginator($res, new UserShopTransformer());
        }
        return $this->api([], false, 405, '获取失败');
    }

    //扫描会员加入门店测试代码
    public function test()
    {
        $str = 'O2O_shop##1##6_0##ooGxkwgpOofFmH3Hy8noUsK2Atj803333';

        $arr = explode('##', $str);
        $shop_id = $arr[1];
        $clerk = explode('_', $arr[2]);
        $open_id = last($arr);
        $input = ['shop_id' => $shop_id, 'clerk_id' => $clerk[0], 'open_id' => $open_id];


        if (!$this->userShopRepository->findWhere(['shop_id' => $shop_id, 'open_id' => $open_id])->first()) {
            $this->userShopRepository->create($input);
        }

//        if ($user = UserBind::where(['type' => 'wechat', 'open_id' => $open_id])->first()) {
//            $input['user_id'] = $user->user_id;
//            //判断是否领会员卡
//            $card = $this->cardRepository->getCardByUserId($user->user_id)->first();
//            if ($card == null || $card->status == false) {
//                return $this->api($card, false, 405, '会员未领会员卡或未激活，添加失败');
//            }
//        };
//        $user = $this->userShopRepository->findOrCreate($input);
//
//        if ($user->user_id == null) {
//            return $this->api([], false, 405, '请会员完成注册并绑定微信,添加失败');
//        }
//        return $this->api([], true, 200, '会员添加成功');
    }


    public function info($user_id)
    {
        $data = $this->userShopRepository->getUserInfoByUserId($user_id);
        $user = $this->replaceUserInfo($data);
        return $this->api($user, true, 200, '');
    }


    protected function replaceUserInfo($info)
    {
        $name = $info->name;
        $mobile = $info->mobile;
        $email = $info->email;
        $qq = $info->qq;


        if ($name) {
            $strlen = mb_strlen($name, 'utf-8');
            $firstStr = mb_substr($name, 0, 1, 'utf-8');
            $lastStr = mb_substr($name, -1, 1, 'utf-8');
            $s_name = $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
            $info->s_name = $s_name;
        }

        if ($mobile) {
            $s_mobile = substr_replace($mobile, '****', 3, 4);
            $info->s_mobile = $s_mobile;
        }

        if ($email) {
            $s_email = substr_replace($email, '***', 0, 3);
            $info->s_email = $s_email;
        }

        if ($qq) {
            $s_qq = substr_replace($qq, '****', 0, 4);
            $info->s_qq = $s_qq;
        }
        $info->userLogin = $info->loginLog->last();

        return $info;
    }


    protected function CheckPermissions($shop_id, $user_id)
    {
        if ($this->userShopRepository->getUserInfoByShopId($shop_id, $user_id)) {
            return true;
        }
        return false;
    }

    //优惠券
    public function getCoupon($user_id)
    {

        $clerk = auth('clerk')->user();

        $type = null;
        if (request('type') == 1) {
            $type = request('type');
        } elseif (request('type') == 0) {
            $type = request('type');
        }


        /*if (!$this->CheckPermissions($clerk->shop_id, $user_id)) {
            return $this->api([], false, 400, '');
        };*/

        if (empty(request('is_active')) AND request('is_active') === '') {
            return $this->api('', false, 400, '无效请求,缺少请求参数');
        }

        if (request('is_active') == 0) {
            $coupons = $this->couponRepository->findInvalidByUser($user_id, $type);
        } elseif (request('is_active') == 1) {
            $coupons = $this->couponRepository->findActiveByUser($user_id, $type);
        } else {
            $coupons = $this->couponRepository->findUsedByUser($user_id);
        }

        return $this->response()->paginator($coupons, new CouponsTransformer());
    }

    //积分
    public function getPoint($user_id)
    {
        $clerk = auth('clerk')->user();
        /*if (!$this->CheckPermissions($clerk->shop_id, $user_id)) {
            return $this->api([], false, 400, '');
        };*/
        $type = request('type');
        return $this->userPoint($user_id, $type);
    }


    public function userPoint($id, $type = null)
    {
        $point = $this->pointRepository->getSumPoint($id, $type);
        $pointValid = $this->pointRepository->getSumPointValid($id, $type);
        $pointFrozen = $this->pointRepository->getSumPointFrozen($id, $type);
        $pointOverValid = $this->pointRepository->getSumPointOverValid($id, $type);
        $pointUsed = Point::where('user_id', $id)->where('value', '<', 0)->sum('value');

        $data = [
            'point' => $point,
            'pointValid' => $pointValid,
            'pointFrozen' => $pointFrozen,
            'pointOverValid' => $pointOverValid,
            'pointUsed' => number_format(abs($pointUsed), 2, ".", "")
        ];

        return $this->api($data, true, 200, '');
    }


    public function pointList($user_id)
    {

        $clerk = auth('clerk')->user();
        /*if (!$this->CheckPermissions($clerk->shop_id, $user_id)) {
            return $this->api([], false, 400, '');
        };*/
        $type = request('type') ? request('type') : 'default';
        $balance = request('balance') ? request('balance') : '';
        $data = [];
        if ($balance == 'in') {
            $data = Point::where('user_id', $user_id)->where('type', $type)->where('status', 1)->where('value', '>', 0)->orderBy('created_at', 'desc')->paginate(10);
        } elseif ($balance == 'out') {
            $data = Point::where('user_id', $user_id)->where('type', $type)->where('status', 1)->where('value', '<', 0)->orderBy('created_at', 'desc')->paginate(10);
        } else {
            $data = Point::where('user_id', $user_id)->where('type', $type)->where('status', 1)->orderBy('created_at', 'desc')->paginate(10);
        }
        return $this->response()->paginator($data, new PointTransformer());

    }


    public function search(Request $request)
    {

        $clerk = auth('clerk')->user();

        $username = $request->input('username');

        if (is_null($model = config('auth.providers.users.model'))) {
            throw new RuntimeException('Unable to determine clerk model from configuration.');
        }

        $shopID = $clerk->shop_id;
        if (isMobile($username)) {
            $shopID = 0;
        }
        $users = $this->userShopRepository->getUserByCondition($username, $shopID);

        /*$res = $this->userShopRepository->searchUserByUserName($clerk->shop_id, $username);

        $rest = $this->userShopRepository->searchUserByUserNameBase($clerk->shop_id, $username);

        $new = array_merge($res->toArray(), $rest->toArray());

        if (count($new)) {
            $arr_user = [];
            $new_data = [];
            foreach ($new as $k => $item) {
                if (!in_array($item['user_id'], $arr_user)) {
                    $arr_user[] = $item['user_id'];
                    $new_data[] = $item;
                }
            }
            return $this->api($new_data, true, 200, '');
        }*/

        return $this->api($users, true, 200, '');

    }


}